package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// Cors 允许跨域请求(全局)
func Cors() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 设置跨域请求
		ctx.Header("Access-Control-Allow-Credentials", "true")
		ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("Origin"))
		// 前端axios请求时, 如果有credentials: "include"参数, 不允许设置为"*"
		// c.Header("Access-Control-Allow-Origin", "*")
		ctx.Header("Access-Control-Allow-Headers", "Aud,Authorization,Namespace,Content-Type,Cache-Control,X-Requested-With")
		ctx.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")

		// 处理OPTIONS请求，直接返回200
		if ctx.Request.Method == http.MethodOptions {
			ctx.AbortWithStatus(200)
			return
		}

		ctx.Next()
	}
}
